import React, { useState, useEffect } from 'react';

const NumberCounter = ({ targetNumber, intervalTime = 10, duration = 600, fontSize = '1.3vw' }) => {
  const [currentNumber, setCurrentNumber] = useState(0);

  // 格式化数字，千位加分号
  const formatNumber = (num) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  useEffect(() => {
    let startTimestamp;
    const step = (timestamp) => {
      if (!startTimestamp) startTimestamp = timestamp;
      const progress = timestamp - startTimestamp;
      const percentage = Math.min(progress / duration, 1);
      const newNumber = currentNumber + (targetNumber - currentNumber) * percentage;
      setCurrentNumber(parseFloat(newNumber.toFixed(2))); // 保留两位小数

      if (progress < duration) {
        requestAnimationFrame(step);
      } else {
        setCurrentNumber(parseFloat(targetNumber.toFixed(2))); // 确保最终结果正确
      }
    };

    requestAnimationFrame(step);

    return () => {
      // 清除可能仍在进行中的动画帧回调
      setCurrentNumber(targetNumber);
    };
  }, [targetNumber, duration]);

  return (
    <span style={{ fontWeight: '600', fontSize: fontSize }}>
      {formatNumber(currentNumber)}
    </span>
  );
};

export default NumberCounter;
